package com.example.sunmiv1.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.OnlineOrderAdapter;
import com.example.sunmiv1.adapter.OnlineOrderPopupAdapter;
import com.example.sunmiv1.entity.OnlineOrderBean;
import com.example.sunmiv1.entity.TurnoverBean;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OnlineOrderActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.onlineOrder_edit)
    EditText onlineOrderEdit;
    @BindView(R.id.onlineOrder_search)
    ImageView onlineOrderSearch;
    @BindView(R.id.onlineOrder_code)
    ImageView onlineOrderCode;
    @BindView(R.id.onlineOrder_listView)
    PullToRefreshListView onlineOrderListView;
    @BindView(R.id.onlineOrder_popup_listView)
    ListView onlineOrderPopupListView;
    @BindView(R.id.onlineOrder_popup_sure)
    TextView onlineOrderPopupSure;
    @BindView(R.id.onlineOrder_popup_inner)
    LinearLayout onlineOrderPopupInner;
    @BindView(R.id.onlineOrder_popup_linear)
    LinearLayout onlineOrderPopupLinear;
    @BindView(R.id.onlineOrder_take_pickCode)
    EditText onlineOrderTakePickCode;
    @BindView(R.id.onlineOrder_take_submit)
    TextView onlineOrderTakeSubmit;
    @BindView(R.id.onlineOrder_take_inner)
    LinearLayout onlineOrderTakeInner;
    @BindView(R.id.onlineOrder_take_linear)
    LinearLayout onlineOrderTakeLinear;
    @BindView(R.id.onlineOrder_take_scan)
    ImageView onlineOrderTakeScan;
    @BindView(R.id.onlineOrder_delivery_shop)
    RadioButton onlineOrderDeliveryShop;
    @BindView(R.id.onlineOrder_delivery_dada)
    RadioButton onlineOrderDeliveryDada;
    @BindView(R.id.onlineOrder_delivery_spinner)
    Spinner onlineOrderDeliverySpinner;
    @BindView(R.id.onlineOrder_delivery_submit)
    TextView onlineOrderDeliverySubmit;
    @BindView(R.id.onlineOrder_delivery)
    LinearLayout onlineOrderDelivery;
    @BindView(R.id.onlineOrder_pass_pass)
    EditText onlineOrderPassPass;
    @BindView(R.id.onlineOrder_pass_login)
    TextView onlineOrderPassLogin;
    @BindView(R.id.onlineOrder_pass_confirm)
    TextView onlineOrderPassConfirm;
    @BindView(R.id.onlineOrder_pass_linear)
    LinearLayout onlineOrderPassLinear;
    @BindView(R.id.onlineOrder_login_phone)
    EditText onlineOrderLoginPhone;
    @BindView(R.id.onlineOrder_login_pass)
    EditText onlineOrderLoginPass;
    @BindView(R.id.onlineOrder_login_cancel)
    TextView onlineOrderLoginCancel;
    @BindView(R.id.onlineOrder_login_confirm)
    TextView onlineOrderLoginConfirm;
    @BindView(R.id.onlineOrder_login_linear)
    LinearLayout onlineOrderLoginLinear;
    @BindView(R.id.onlineOrder_uuDelivery_info)
    TextView onlineOrderUuDeliveryInfo;
    @BindView(R.id.onlineOrder_uuDelivery_phone)
    EditText onlineOrderUuDeliveryPhone;
    @BindView(R.id.onlineOrder_uuDelivery_need)
    RadioButton onlineOrderUuDeliveryNeed;
    @BindView(R.id.onlineOrder_uuDelivery_noNeed)
    RadioButton onlineOrderUuDeliveryNoNeed;
    @BindView(R.id.onlineOrder_uuDelivery_content)
    EditText onlineOrderUuDeliveryContent;
    @BindView(R.id.onlineOrder_uuDelivery_cancel)
    TextView onlineOrderUuDeliveryCancel;
    @BindView(R.id.onlineOrder_uuDelivery_sure)
    TextView onlineOrderUuDeliverySure;
    @BindView(R.id.onlineOrder_uuDelivery_linear)
    LinearLayout onlineOrderUuDeliveryLinear;
    @BindView(R.id.onlineOrder_cancelUu_reason)
    EditText onlineOrderCancelUuReason;
    @BindView(R.id.onlineOrder_cancelUu_cancel)
    TextView onlineOrderCancelUuCancel;
    @BindView(R.id.onlineOrder_cancelUu_sure)
    TextView onlineOrderCancelUuSure;
    @BindView(R.id.onlineOrder_cancelUu_linear)
    LinearLayout onlineOrderCancelUuLinear;
    @BindView(R.id.onlineOrder_pass_inLinear)
    LinearLayout onlineOrderPassInLinear;
    @BindView(R.id.online_searchType)
    Spinner onlineSearchType;
    @BindView(R.id.online_time)
    Spinner onlineTime;
    @BindView(R.id.online_pickup_type)
    Spinner onlinePickUpType;
    @BindView(R.id.online_type)
    Spinner onlineType;

    private Context context;
//    private OnlineOrderBean onlineOrderBean;
    private TurnoverBean onlineOrderBean;
//    private List<OnlineOrderBean.OrderBean> list;
    private List<TurnoverBean.OrderBean> list;
    private List<OnlineOrderBean.OrderBean.GoodInfoBean> popuplist;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private OnlineOrderAdapter onlineOrderAdapter;
    private OnlineOrderPopupAdapter onlineOrderPopupAdapter;

    private int page = 1;//第幾頁的數據
    private int limit = 10;//每頁顯示幾條數據
    private int user_type = 1;//1:用戶；2:店長

    private List<String> deliveryList = new ArrayList<>();

    private int flag1 = 1;//1是訂單搜索，2是掃描提貨碼
    public static int flag = 0;//用來判斷是商城訂單，還是拼團還是秒殺,預售的集合

    private int deliveryType = 0;//0:商家配送，1:達達配送，2:UU跑腿

    private int select = 0;//點擊的第幾條數據

    boolean isFirst = true;//防止spinner第一次加載兩次數據
    boolean isFirst2 = true;//防止spinner第一次加載兩次數據
    boolean isFirst3 = true;//防止spinner第一次加載兩次數據
    private int status = 0;//選擇的第幾個篩選條件
    private int searchType = 1;//搜索類型：1，訂單號搜索；2，手機號搜索 3,串碼搜索
    private int type = 1;//1是今日，2昨日，3是本週，4是其他
    private List<String> typeList = new ArrayList<>();
    private List<String> flagList = new ArrayList<>();
    private List<String> searchTypeList = new ArrayList<>();
    private List<String> statusList = new ArrayList<>();


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
                    onlineOrderListView.onRefreshComplete();
                    page++;
                    for (int i = 0; i < onlineOrderBean.getOrder().size(); i++) {
                        TurnoverBean.OrderBean orderBean=onlineOrderBean.getOrder().get(i);
                        orderBean.setOrder_genre(flagList.get(flag)+"訂單");
                        list.add(onlineOrderBean.getOrder().get(i));
                    }
                    setOnlineOrderAdapter();
                    break;
                case 2:
                    loadingDialog.dismiss();
                    onlineOrderListView.onRefreshComplete();
                    Toast.makeText(context, "查詢失敗", Toast.LENGTH_SHORT).show();
                    setOnlineOrderAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_online_order);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.onlineOrderTitle);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        list.clear();
        setOnlineOrderAdapter();
        getOrder();
//        getOnlineOrder(0);
    }

    private void setOnlineGoodType() {
        //往會員來源Spinner中添加數據
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, typeList);  //創建一個數組適配器
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        onlineType.setAdapter(adapter);
    }

    private void setOnlinePickUpType() {
        //往會員來源Spinner中添加數據
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, flagList);  //創建一個數組適配器
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        onlinePickUpType.setAdapter(adapter);
    }

    private void setOnlineTime() {
        //往會員來源Spinner中添加數據
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, statusList);  //創建一個數組適配器
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        onlineTime.setAdapter(adapter);
    }

    private void setOnlineSearchType() {
        //往會員來源Spinner中添加數據
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, searchTypeList);  //創建一個數組適配器
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        onlineSearchType.setAdapter(adapter);
    }

    private void initData() {
        list = new ArrayList<>();
        popuplist = new ArrayList<>();
        deliveryList.add("商家配送");
        deliveryList.add("達達配送");
        setDeliveryTypeAdapter();
        list = new ArrayList<>();
        initScreenList();
        flagList.add("商城");
        flagList.add("拼團");
        flagList.add("秒殺");
        flagList.add("預售");
        setOnlinePickUpType();

        searchTypeList.add("訂單號");
        searchTypeList.add("會員");
        searchTypeList.add("串碼");
        searchTypeList.add("自提碼");
        setOnlineSearchType();

        statusList.add("今日");
        statusList.add("昨日");
        statusList.add("本週");
        statusList.add("其他");
        setOnlineTime();

        onlinePickUpType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isFirst2) {
                    isFirst2 = false;
                    return;
                }
                flag = position;
                page = 1;
                list.clear();
                setOnlineOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        onlineTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type = position+1;
                if (isFirst3) {
                    isFirst3 = false;
                    return;
                }
                page = 1;
                list.clear();
                setOnlineOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        onlineSearchType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                searchType = position + 1;
                String hint = "";
                switch (position) {
                    case 0:
                        hint = "請輸入訂單號";
                        break;
                    case 1:
                        hint = "請輸入會員";
                        break;
                    case 2:
                        hint = "請輸入串碼";
                        break;
                    case 3:
                        hint = "請輸入自提碼";
                        break;
                    default:
                        hint = "";
                        break;
                }
                onlineOrderEdit.setHint(hint);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        onlineType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isFirst) {
                    isFirst = false;
                    return;
                }
                status = position;
                page = 1;
                list.clear();
                setOnlineOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        
        onlineOrderDeliverySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                deliveryType = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        onlineOrderListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
//                getOnlineOrder(0);
                getOrder();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//                getOnlineOrder(0);
                getOrder();
            }
        });
    }

    private void initScreenList() {
        typeList.clear();
        typeList.add("全部");
        typeList.add("待自提");
        typeList.add("已自提");
        typeList.add("待發貨");
        typeList.add("配送中");
        typeList.add("已收貨");
        typeList.add("正常訂單");
//        typeList.add("待退款");
//        typeList.add("已退款");
//        typeList.add("購買訂單");
        if (flag1 == 3) {
            typeList.add("待付尾款已過期");
            typeList.add("待付尾款未過期");
            typeList.add("已付尾款");
        }
        setOnlineGoodType();
    }

    private void setDeliveryTypeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, deliveryList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop);
        onlineOrderDeliverySpinner.setAdapter(arrayAdapter);
    }

    private void setOnlineOrderAdapter() {
        if (onlineOrderAdapter == null) {
            onlineOrderAdapter = new OnlineOrderAdapter(context, list);
            onlineOrderListView.setAdapter(onlineOrderAdapter);
        } else {
            onlineOrderAdapter.notifyDataSetChanged();
        }
        onlineOrderAdapter.onclick((index, type) -> {
            select = index;
            if (type == 1) {//查看詳情
                Intent intent = new Intent(context, OnlineOrderDetailActivity.class);
                intent.putExtra("good", (Serializable) list.get(index));
                startActivity(intent);
                /*popuplist.clear();
                for (int i = 0; i < list.get(index).getGood_info().size(); i++) {
                    popuplist.add(list.get(index).getGood_info().get(i));
                }
                if (popuplist.size() > 6) {
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) onlineOrderPopupListView.getLayoutParams();
                    layoutParams.height = Tools.getScreenHeight(context) / 3;
                    onlineOrderPopupListView.setLayoutParams(layoutParams);
                } else {
                    ViewGroup.LayoutParams layoutParams = onlineOrderPopupListView.getLayoutParams();
                    layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    onlineOrderPopupListView.setLayoutParams(layoutParams);
                }
                onlineOrderPopupAdapter = new OnlineOrderPopupAdapter(context, popuplist);
                onlineOrderPopupListView.setAdapter(onlineOrderPopupAdapter);
                onlineOrderPopupLinear.setVisibility(View.VISIBLE);*/
            } else if (type == 2) {
                if ("2".equals(list.get(index).getRefund_status())) {
                    onlineOrderPassPass.postDelayed(() -> onlineOrderPassPass.requestFocus(), 500);
                    onlineOrderPassLinear.setVisibility(View.VISIBLE);
                } else {
                    if ("1".equals(list.get(index).getPickup_type())) {//自提
                        onlineOrderTakeLinear.setVisibility(View.VISIBLE);
                        onlineOrderTakePickCode.postDelayed(() -> onlineOrderTakePickCode.requestFocus(), 200);
                    } else {//配送
//                        onlineOrderDelivery.setVisibility(View.VISIBLE);
                        Intent intent = new Intent(context, DeliveryGoodsActivity.class);
                        intent.putExtra("id", list.get(index).getId());
                        intent.putExtra("orderNo", list.get(index).getOrder_no());
                        intent.putExtra("pickupType", list.get(index).getPickup_type());
                        startActivity(intent);
                    }
                }
            } else {
//                    if(TextUtils.isEmpty(list.get(select).getRefund_order_no())){
//                        Toast.makeText(context, "訂單信息錯誤", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                onlineOrderPassLinear.setVisibility(View.VISIBLE);
            }
        });
    }

    @OnClick({R.id.title_back, R.id.onlineOrder_search, R.id.onlineOrder_code, R.id.onlineOrder_popup_sure, R.id.onlineOrder_popup_linear,
            R.id.onlineOrder_popup_inner, R.id.onlineOrder_take_submit, R.id.onlineOrder_take_inner, R.id.onlineOrder_take_linear,
            R.id.onlineOrder_take_scan, R.id.onlineOrder_delivery_submit, R.id.onlineOrder_delivery,
            R.id.onlineOrder_pass_login, R.id.onlineOrder_pass_confirm, R.id.onlineOrder_pass_linear, R.id.onlineOrder_pass_inLinear,
            R.id.onlineOrder_login_cancel, R.id.onlineOrder_login_confirm, R.id.onlineOrder_login_linear,
            /*UU配送*/
            R.id.onlineOrder_uuDelivery_linear, R.id.onlineOrder_uuDelivery_cancel, R.id.onlineOrder_uuDelivery_sure,
            /*取消UU跑腿配送*/
            R.id.onlineOrder_cancelUu_linear, R.id.onlineOrder_cancelUu_cancel, R.id.onlineOrder_cancelUu_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.onlineOrder_pass_inLinear:
                break;
            case R.id.onlineOrder_cancelUu_linear:
                break;
            case R.id.onlineOrder_cancelUu_cancel:
                onlineOrderCancelUuReason.setText("");
                onlineOrderCancelUuLinear.setVisibility(View.GONE);
                break;
            case R.id.onlineOrder_cancelUu_sure:
                if (TextUtils.isEmpty(onlineOrderCancelUuReason.getText().toString().trim())) {
                    Toast.makeText(context, "取消配送原因不能爲空", Toast.LENGTH_SHORT).show();
                    return;
                }
                CancelUUDelivery();
                break;
            case R.id.onlineOrder_uuDelivery_linear:
                break;
            case R.id.onlineOrder_uuDelivery_cancel:
                onlineOrderUuDeliveryInfo.setText("");
                onlineOrderUuDeliveryPhone.setText("");
                onlineOrderUuDeliveryNoNeed.setChecked(true);
                onlineOrderUuDeliveryContent.setText("");
                onlineOrderUuDeliveryLinear.setVisibility(View.GONE);
                break;
            case R.id.onlineOrder_uuDelivery_sure:
                DeliveryOrder();
                break;

            case R.id.onlineOrder_login_cancel:
                user_type = 1;
                onlineOrderLoginLinear.setVisibility(View.GONE);
                onlineOrderPassLinear.setVisibility(View.VISIBLE);
                onlineOrderPassPass.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onlineOrderPassPass.requestFocus();
                    }
                }, 500);
                break;
            case R.id.onlineOrder_login_confirm:
                if (TextUtils.isEmpty(onlineOrderLoginPhone.getText().toString()) || onlineOrderLoginPhone.getText().toString().length() != 11) {
                    Toast.makeText(context, "請輸入正確的手機號", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(onlineOrderLoginPass.getText().toString())) {
                    Toast.makeText(context, "請輸入密碼", Toast.LENGTH_SHORT).show();
                    return;
                }
                Refund();
                break;
            case R.id.onlineOrder_login_linear:
                user_type = 1;
                onlineOrderLoginLinear.setVisibility(View.GONE);
                onlineOrderPassLinear.setVisibility(View.VISIBLE);
                onlineOrderPassPass.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onlineOrderPassPass.requestFocus();
                    }
                }, 500);
                break;
            case R.id.onlineOrder_pass_linear:
                onlineOrderPassPass.setText("");
                onlineOrderPassLinear.setVisibility(View.GONE);
                break;
            case R.id.onlineOrder_pass_login:
                onlineOrderPassPass.setText("");
                user_type = 2;
                onlineOrderPassLinear.setVisibility(View.GONE);
                onlineOrderLoginLinear.setVisibility(View.VISIBLE);
                onlineOrderLoginPhone.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onlineOrderLoginPhone.requestFocus();
                    }
                }, 500);
                break;
            case R.id.onlineOrder_pass_confirm:
                if (TextUtils.isEmpty(onlineOrderPassPass.getText().toString())) {
                    Toast.makeText(context, "請輸入退款密碼", Toast.LENGTH_SHORT).show();
                    return;
                }
                Refund();
                break;
            case R.id.onlineOrder_delivery:
                onlineOrderDelivery.setVisibility(View.GONE);
                break;
            case R.id.onlineOrder_delivery_submit:
                switch (deliveryType) {
                    case 0:
                        DeliveryOrder();
                        break;
                    case 1:
                        DeliveryOrder();
                        break;
                    case 2:
                        GetUUDeliveryInfo();
                        break;
                }
                break;
            case R.id.onlineOrder_take_scan:
                flag1 = 2;
                startQrCode(flag1);
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.onlineOrder_search:
                if ("".equals(onlineOrderEdit.getText().toString())) {
                    Toast.makeText(context, "請輸入要搜索的訂單號", Toast.LENGTH_SHORT).show();
                    return;
                }
                page = 1;
//                getOnlineOrder(1);
                getOrder();
                break;
            case R.id.onlineOrder_code:
                flag1 = 1;
                startQrCode(flag1);
                break;
            case R.id.onlineOrder_popup_sure:
                onlineOrderPopupLinear.setVisibility(View.GONE);
                break;
            case R.id.onlineOrder_popup_linear:
                onlineOrderPopupLinear.setVisibility(View.GONE);
                break;
            case R.id.onlineOrder_popup_inner:
                break;
            case R.id.onlineOrder_take_submit:
                if (TextUtils.isEmpty(onlineOrderTakePickCode.getText().toString())) {
                    Toast.makeText(context, "請輸入提貨碼", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if (onlineOrderTakePickCode.getText().toString().trim().equals(list.get(select).getPickcode())) {
//                    Intent intent = new Intent(context, DeliveryGoodsActivity.class);
//                    intent.putExtra("id", list.get(select).getId());
//                    intent.putExtra("orderNo", list.get(select).getOrder_no());
//                    intent.putExtra("pickupType", list.get(select).getPickup_type());
//                    intent.putExtra("pickupCode", onlineOrderTakePickCode.getText().toString());
//                    startActivity(intent);
//                } else {
//                    Toast.makeText(context, "取貨碼不正確請重新輸入", Toast.LENGTH_SHORT).show();
//                }
                selfMention();
                break;
            case R.id.onlineOrder_take_inner:
                break;
            case R.id.onlineOrder_take_linear:
                onlineOrderTakePickCode.setText("");
                onlineOrderTakeLinear.setVisibility(View.GONE);
                break;
        }
    }

    // 開始掃碼
    private void startQrCode(int flag1) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, flag1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode(flag1);
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            onlineOrderEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            page = 1;
            getOrder();
//            getOnlineOrder(1);
        }
        if (requestCode == 2 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            onlineOrderTakePickCode.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            onlineOrderTakePickCode.setSelection(onlineOrderTakePickCode.getText().toString().length());
            selfMention();
        }
    }

    /**
     * 獲取訂單（新）
     */
    private void getOrder() {
        loadingDialog.show();
        if (page == 1) {
            list.clear();
            setOnlineOrderAdapter();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            if ("".equals(onlineOrderEdit.getText().toString())) {
                jsonObject.put("type", type);
            } else {
                jsonObject.put("type", type);
//                jsonObject.put("judge", search_type);
//                jsonObject.put("order_number", shoppingMallSearch.getText().toString());
                if (searchType == 1 || searchType == 3||searchType == 4) {
                    jsonObject.put("order_number", onlineOrderEdit.getText().toString());
                } else {
                    jsonObject.put("vip_code", onlineOrderEdit.getText().toString());
                }
                if (searchType == 3) {
                    jsonObject.put("judge", 3);
                }else if (searchType==4){
                    jsonObject.put("judge", 2);
                }else {
                    jsonObject.put("judge", 1);
                }
            }
            jsonObject.put("line", 2);
            jsonObject.put("page", page);
            jsonObject.put("num", 20);
            jsonObject.put("status", status);
            String url = "";
            jsonObject.put("order_genre", flag + 1);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.ORDER_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    onlineOrderBean = GsonUtils.JsonToBean(text, TurnoverBean.class);
                    Message msg = new Message();
                    if (onlineOrderBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

//    private void getOnlineOrder(final int type) {
//        loadingDialog.show();
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("storeid", aCache.getAsString("storeid"));
//            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
//            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
//            if ("3".equals(aCache.getAsString("userType"))) {
//                jsonObject.put("operator_id", aCache.getAsString("uid"));
//            }else{
//                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
//            }
//            jsonObject.put("page", page);
//            jsonObject.put("num", limit);
//            if (!"".equals(onlineOrderEdit.getText().toString())) {
//                jsonObject.put("order_number", onlineOrderEdit.getText().toString());
//            }
//            HttpUtils.post(context, Common.GET_ONLINE_ORDER, jsonObject, new TextCallBack() {
//                @Override
//                protected void onSuccess(String text) {
//                    onlineOrderBean = GsonUtils.JsonToBean(text, OnlineOrderBean.class);
//                    Message msg = new Message();
//                    if (onlineOrderBean.getStatus() == 1 && onlineOrderBean.getOrder().size() > 0) {
//                        onlineOrderEdit.setText("");
//                        if (type == 1) {
//                            list.clear();
//                        }
//                        msg.what = 1;
//                    } else {
//                        onlineOrderEdit.setText("");
//                        msg.what = 2;
//                    }
//                    handler.sendMessage(msg);
//                }
//
//                @Override
//                protected void onFailure(ResponseException e) {
//                    loadingDialog.dismiss();
//                    onlineOrderListView.onRefreshComplete();
//                }
//            });
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }

    /*自提*/
    private void selfMention() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", list.get(select).getOrder_no());
            jsonObject.put("pick_code", onlineOrderTakePickCode.getText().toString());
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.SELF_MENTION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            onlineOrderDelivery.setVisibility(View.GONE);
                            onlineOrderTakeLinear.setVisibility(View.GONE);
                            page = 1;
                            list.clear();
                            getOrder();
//                            getOnlineOrder(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void DeliveryOrder() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", list.get(select).getOrder_no());
            jsonObject.put("type", deliveryType + 1);
            if (onlineOrderUuDeliveryNoNeed.isChecked()) {//不需要保溫箱
                jsonObject.put("special_type", 0);
            } else {
                jsonObject.put("special_type", 1);
            }
            jsonObject.put("uu_phone", onlineOrderUuDeliveryPhone.getText().toString());
            jsonObject.put("note", onlineOrderUuDeliveryContent.getText().toString());
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.DELIVERY_ORDER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            onlineOrderDeliveryShop.setChecked(true);
                            onlineOrderDelivery.setVisibility(View.GONE);
                            page = 1;
                            list.clear();
                            getOrder();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void Refund() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", list.get(select).getOrder_no());
            jsonObject.put("user_type", user_type);
            if (user_type == 2) {
                jsonObject.put("username", onlineOrderLoginPhone.getText().toString());
                jsonObject.put("refund_code", onlineOrderLoginPass.getText().toString());
            } else {
                jsonObject.put("username", "");
                jsonObject.put("refund_code", onlineOrderPassPass.getText().toString());
            }
            if (list.get(select).getStatus().equals("1")) {
                jsonObject.put("return_delivery_fee", 2);
            } else {
                jsonObject.put("return_delivery_fee", 2);
            }
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.REFUND, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            onlineOrderLoginPhone.setText("");
                            onlineOrderLoginPass.setText("");
                            onlineOrderPassPass.setText("");
                            onlineOrderPassLinear.setVisibility(View.GONE);
                            list.clear();
                            page = 1;
                            getOrder();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取UU配送信息
     */
    private void GetUUDeliveryInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", list.get(select).getOrder_no());
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_UU_DELIVERY_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            onlineOrderDeliverySpinner.setSelection(0);
                            onlineOrderDelivery.setVisibility(View.GONE);
                            onlineOrderUuDeliveryInfo.setText(json.getString("msg"));
                            onlineOrderUuDeliveryLinear.setVisibility(View.VISIBLE);
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void CancelUUDelivery() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", list.get(select).getOrder_no());
            jsonObject.put("reason", onlineOrderCancelUuReason.getText().toString().trim());
//            jsonObject.put("reason_id", reasonList.get(reason_index).getReasonid());
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.CANCEL_UU_DELIVERY, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                            onlineOrderCancelUuReason.setText("");
                            onlineOrderCancelUuLinear.setVisibility(View.GONE);
                            page = 1;
                            list.clear();
                            getOrder();
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
